const Router = require('koa-router')
const fs = require('fs')
const path = require('path')
const debug = require('debug')('fileuploads')
const jwt = require('jsonwebtoken')

// 实例化路由
const router = new Router()

const ConfigManager = require('../../lib/config.js')
const tools = require('../../servse/tools.js')
const db = require('../../servse/db.js')

/**
 * @router GET api/file/getFile
 * @desc 获取个人归属的文件接口
 * @access 接口共有
 */
router.get('/getFile', async (ctx, next) => {
  const token = ctx.header.authorization
  if (token) {
    await jwt.verify(token, ConfigManager.getSecretKey(), async (err, decoded) => {
      if (err) {
        ctx.status = 400
        ctx.body = {
          errcode: 1,
          errmsg: err
        }
        return ctx.body
      } else {
        const userId = decoded.id
        const result = await db.findUserFile(userId)
        ctx.status = 200
        ctx.body = {
          errcode: 0,
          data: result
        }
        return ctx.body
      }
    })
  }
})

/**
 * @router POST api/file/upload
 * @desc 文件上传
 * @access 接口共有
 */
router.post('/upload', async (ctx, next) => {
  const token = ctx.header.authorization
  tools.vetify(token, function (msg) {
    if (msg.code === 1) {
      const file = ctx.request.files.file // 获取上传文件
      const ext = '.' + file.name.split('.').pop() // 获取上传文件扩展名

      // 重命名文件
      const basename = tools.getname()
      const filePath = path.join(__dirname, String(ConfigManager.getWordPath())) + basename + `${ext}`
      const pdfPath = path.join(__dirname, String(ConfigManager.getPdfPath())) + basename + '.pdf'

      if (ext === '.pdf') {
        tools.ifPdf(file, pdfPath, function () {
          // 获取页数
          tools.getnumpages(pdfPath, function (numpages) {
            const newFile = ({
              fileUuid: basename,
              userId: msg.userinfo.id,
              userName: msg.userinfo.name,
              fileName: ctx.request.body.fileName,
              filePage: numpages,
              type: ext,
              size: file.size
            })
            db.savaFile(newFile)
            db.updateAddUserFile(msg.userinfo.id)
            tools.setflag(1)
          })
        })
      } else {
        tools.noPdf(file, filePath, function () {
          debug('WordtoPdf Starting...')
          tools.setflag(0)
          tools.WordtoPdf(filePath, pdfPath, function () {
            debug('转化完成')
            tools.getnumpages(pdfPath, function (numpages) {
              debug('获取页数为:', numpages)
              const newFile = ({
                fileUuid: basename,
                userId: msg.userinfo.id,
                userName: msg.userinfo.name,
                fileName: ctx.request.body.fileName,
                filePage: numpages,
                type: ext,
                size: file.size
              })
              db.savaFile(newFile)
              db.updateAddUserFile(msg.userinfo.id)
              tools.setflag(1)
            })
          })
        })
      }
      // console.log(tools.getflag())
      if (!tools.getflag()) {
        ctx.status = 200
        ctx.body = {
          errcode: 0,
          errmsg: '上传中',
          fileUuid: basename
        }
        return ctx.body
      }
      if (tools.getflag() === 1) {
        tools.setflag(0)
        ctx.status = 200
        ctx.body = {
          errcode: 0,
          errmsg: '上传成功',
          fileUuid: basename
          // httpUrl: `${ctx.origin}/pdf/${basename}` + '.pdf'
        }
        return ctx.body
      }
    } else {
      ctx.status = 400
      ctx.body = {
        errcode: 1,
        errmsg: msg.message
      }
      return ctx.body
    }
  })
})

/**
 * @router POST api/file/listen
 * @desc 监听文件上传
 * @access 接口共有
 */
router.get('/:Uuid/status', async (ctx, next) => {
  // 获取文件Uuid
  const fileUuid = ctx.params.Uuid
  const result = await db.findFilestat(fileUuid)
  if (result.length > 0) {
    ctx.body = {
      errcode: 0,
      data: {
        status: 'finish'
      }
    }
    return ctx.body
  } else {
    ctx.status = 200
    ctx.body = {
      errcode: 0,
      data: {
        status: 'waiting'
      }
    }
    return ctx.body
  }
})

/**
 * @router GET api/file/delete
 * @desc 文件删除
 * @access 接口共有
 */
router.get('/delete/:fileUuid', async (ctx, next) => {
  const token = ctx.header.authorization
  if (token) {
    await jwt.verify(token, ConfigManager.getSecretKey(), async (err, decoded) => {
      if (err) {
        ctx.status = 400
        ctx.body = {
          errcode: 1,
          errmsg: err
        }
        return ctx.body
      } else {
        // 获取文件id
        const fileUuid = ctx.params.fileUuid
        const result = await db.findFilestat(fileUuid)
        // console.log(fileUuid)
        if (result.length > 0) {
          if (result[0].type === '.pdf') {
            const fileName = path.join(__dirname, String(ConfigManager.getPdfPath())) + result[0].fileUuid + '.pdf'
            fs.unlink(fileName, function (err) {
              if (err) {
                throw err
              }
              debug('成功删除了文件')
              db.reduceUserFile(decoded.id)
            })
            ctx.status = 200
            ctx.body = {
              errcode: 0,
              data: {
                status: 'success'
              }
            }
            db.deleteFile(fileUuid)
            return ctx.body
          } else {
            const filelist = []
            const fileName1 = path.join(__dirname, String(ConfigManager.getPdfPath())) + result[0].fileUuid + '.pdf'
            const fileName2 = path.join(__dirname, String(ConfigManager.getWordPath())) + result[0].fileUuid + result[0].type
            filelist[0] = fileName1
            filelist[1] = fileName2
            tools.deleteFile(filelist, function () {
              ctx.status = 200
              ctx.body = {
                errcode: 0,
                data: {
                  status: 'success'
                }
              }
              db.deleteFile(fileUuid)
              db.reduceUserFile(decoded.id)
              return ctx.body
            })
          }
        } else {
          ctx.status = 200
          ctx.body = {
            errcode: 0,
            data: {
              status: 'fail'
            }
          }
          return ctx.body
        }
      }
    })
  }
})

module.exports = router.routes()
